#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>


int main() {
	int sock, listener;
	struct sockaddr_in addr;
	char buf[1024];
	int bytes_read;

	listener = socket(AF_INET, SOCK_STREAM, 0);
	if (listener < 0) {
		perror("initialization of socket failed");
		exit(errno);
	}
	printf("listen\n");
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6006);
	addr.sin_addr.s_addr = INADDR_ANY;
	if (bind(listener, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		perror("bind failed");
		exit(errno);
	}
	printf("bind\n");
	listen(listener, 1);
	while (1) {
		sock = accept(listener, NULL, NULL);
		if (sock < 0) {
			perror("accept failed");
			exit(errno);	
		}
		printf("accept\n");
		while (1) {
			bytes_read = recv(sock, buf, 1024, 0);
			printf("%s\n", buf);
			if (bytes_read <= 0) break;
			send(sock, buf, bytes_read, 0);
		}
		close(sock);
	}
	return 0;
}
